import Taro, { Component } from '@tarojs/taro';
import { View, Button, Text, Image, ScrollView } from '@tarojs/components';
import classnames from 'classnames';
import NavigationBar from '../../../components/navigationBar/index';
import Empty from '../../../static/public/icon_order.png';
import CardBg from '../electronic-card/img/electronic_card_bg.png';
import CardUsedImg from '../electronic-card/img/electronic_card_used.png';
import CardExpiredImg from '../electronic-card/img/electronic_card_expired.png';
import CardSharedImg from '../electronic-card/img/electronic_card_shared.png';
import CardArrowNone from '../electronic-card/img/electronic_card_sort_arrow_none.png';
import CardArrowTop from '../electronic-card/img/electronic_card_sort_arrow_top.png';
import CardArrowBottom from '../electronic-card/img/electronic_card_sort_arrow_bottom.png';
import CardClaimSuccess from '../electronic-card/img/card_claim_success.png';

import { list, shareLoglist, shareCard, cancelShare } from '../../../services/electronicCard';
import { purchaseGood } from '../../../services/goods';
import { timeFormat, fullImgUrl } from '../../../utils/utils';
import TabBar from '../../../components/tab-bar/index';
import './index.scss';

export default class Index extends Component {

  config = {
    navigationBarTitleText: '我的兑换卡',
    onReachBottomDistance: 50,
  }

  state = {
    pageData: {
      page: 1,
      page_number: 10,
      order_effective: null,
      order_price: null,
    },
    isMore: false,
    isShareMore: false,
    isSearch: false,
    activeDefalut: true,
    activePrice: 0,
    activeEffective: 0,
    navigationBarHeight: Taro.getStorageSync('navigationBarHeight'),
    userInfo: Taro.getStorageSync('userInfo') || null,
    setting: Taro.getStorageSync('setting'),
    HeaderTab: [{
      key: 0,
      val: '未使用'
    }, {
      key: 1,
      val: '已兑换'
    }, {
      key: 2,
      val: '已转赠'
    }, {
      key: 3,
      val: '已失效'
    }],
    status: 0,
    cardRecordList: [],
    cardShareList: [],
    flag: 1,
    statusS: 4,
    isShowShareRemind: false,// 开启转赠弹窗
    share_card: {},// 即将转赠的卡对象
    listCount: [],
    listCount_0: 0, // 每一状态的数量
    listCount_1: 0, // 每一状态的数量
    listCount_2: 0, // 每一状态的数量
    listCount_3: 0, // 每一状态的数量
  };

  componentWillMount() {
  }
  componentDidMount() { }
  componentWillReceiveProps(nextProps, nextContext) { }
  componentWillUnmount() { }
  componentDidShow() {
    this.state.pageData.page = 1;
    this.state.isSearch = false;
    this.init()
    list({
      ...this.state.pageData,
      card_status: 0,
    }).then(res => {
      this.setState({ listCount_0: res.total })
    })
    list({
      ...this.state.pageData,
      card_status: 1,
    }).then(res => {
      this.setState({ listCount_1: res.total })
    })
    shareLoglist({
      ...this.state.pageData,
    }).then(res => {
      this.setState({ listCount_2: res.total })
    })
    list({
      ...this.state.pageData,
      card_status: 3,
    }).then(res => {
      this.setState({ listCount_3: res.total })
    })
  }
  componentDidHide() { }
  componentDidCatchError() { }
  componentDidNotFound() { }

  close() {
    this.props.onClose();
  }


  showList(res, isConcat) {
    if (isConcat) {
      let temp = this.state.cardRecordList.concat(res.list)
      this.setState({
        cardRecordList: temp,
      });
      this.state.isMore = temp.length < res.total
    } else {
      this.setState({
        cardRecordList: res.list
      });
      this.state.isMore = res.list.length < res.total
    }
    this.state.pageData.page++
  }

  showShareList(res, isConcat) {
    if (isConcat) {
      let temp = this.state.cardShareList.concat(res.list)
      this.setState({
        cardShareList: temp,
      });
      this.state.isShareMore = temp.length < res.total
    } else {
      this.setState({
        cardShareList: res.list
      });
      this.state.isShareMore = res.list.length < res.total
    }
    this.state.pageData.page++
  }

  init() {
    console.log('init')
    let status = this.state.status;
    list({
      ...this.state.pageData,
      card_status: this.state.status,
    }).then(res => {
      this.showList(res, false, this.state.status)
      this.setState({
        listCount_0: res.total
      })
    })
  }

  handleTabChange(key) {
    console.log('handleTabChange')
    this.state.isMore = false
    this.state.pageData.page = 1
    this.state.status = key
    if (key === 2) {
      this.setState({ cardRecordList: [] })
      // 卡转赠列表
      shareLoglist({
        ...this.state.pageData,
      }).then(res => {
        this.showShareList(res, this.state.isShareMore);
      })
    } else {
      this.setState({ cardShareList: [] })
      // 卡列表
      list({
        ...this.state.pageData,
        card_status: key,
      }).then(res => {
        this.showList(res, this.state.isMore);
      })
    }
  }

  onScrollToLower() {
    console.log('onScrollToLower')
    if (this.state.status === 2) {
      if (this.state.isShareMore) {
        shareLoglist({
          ...this.state.pageData,
        }).then(res => {
          this.showShareList(res, this.state.isShareMore)
        })
      }
    } else {
      if (this.state.isMore) {
        list({
          ...this.state.pageData,
          card_status: this.state.status
        }).then(res => {
          this.showList(res, this.state.isMore)
        })
      }
    }
  }

  onShareAppMessage(res) {
    //let data = res.target.dataset.item; //取到传入的参数
    let card = this.state.share_card;
    console.log(card)
    let pathUrl = `/subPackageWork/pages/electronic-lp/index?card_id=${card.id}&initiator_id=${this.state.userInfo.id}`;
    // let pathUrl = `/pages/home/index?type=electornic-card&card_id=${card.id}&initiator_id=${this.state.userInfo.id}`;

    shareCard({
      card_id: card.id
    }).then(res => {

    }).catch((err) => {
      if (showToast && err) {
        Taro.showToast({
          title: err.data,
          icon: 'none'
        })
      }
    })
    // 关闭转赠弹窗
    this.hiddenShareRemind();
    return {
      title: `${card.has_goods.share_title}`,
      path: pathUrl,
      imageUrl: `${fullImgUrl(card.has_goods.share_image)}`,
    };
  }

  goShop(goods_id, electronic_card_id) {
    // 跳转到兑换商场
    console.log('使用——兑换商场')

    purchaseGood({
      sku_id: 0,
      goods_id: goods_id,
      num: 1,
      electronic_card_id: electronic_card_id,
    }).then(res => {
      Taro.navigateTo({
        url: `/subPackageWork/pages/electronic-settlement/index`
      })
    })
  }

  showShareRemind(card) {
    // 跳转到兑换商场
    console.log('开启转赠确认弹窗')

    this.setState({
      'isShowShareRemind': true,
      'share_card': card,
    });
    console.log(card)
  }

  hiddenShareRemind() {
    // 跳转到兑换商场
    console.log('取消转赠确认弹窗')

    this.setState({
      'isShowShareRemind': false,
    });
  }

  cancelShare(electronic_card_id) {
    console.log('撤销转赠')
    cancelShare({
      card_id: electronic_card_id,
    }).then(res => {
      Taro.showToast({
        title: res,
        icon: 'none'
      })
      this.state.pageData.page = 1
      this.init();
    })
  }


  // 排序规则。默认综合无排序
  sortDefaultList() {
    const { activeDefalut } = this.state;
    if (!activeDefalut) {
      this.state.activePrice = 0;
      this.state.activeEffective = 0;
      this.state.activeDefalut = true;
    }
    this.sortList();
  }

  // 排序规则
  sortPriceList() {
    const { activePrice } = this.state;
    if (activePrice === 0) {
      this.state.activePrice = 1;
      this.state.pageData.order_price = 'desc';
    } else if (activePrice === 1) {
      this.state.activePrice = 2;
      this.state.pageData.order_price = 'asc';
    } else {
      this.state.activePrice = 0;
      this.state.pageData.order_price = null;
    }
    this.sortList();
  }

  // 排序规则
  sortEffective() {
    const { activeEffective } = this.state;
    if (activeEffective === 0) {
      this.state.activeEffective = 1;
      this.state.pageData.order_effective = 'desc';
    } else if (activeEffective === 1) {
      this.state.activeEffective = 2;
      this.state.pageData.order_effective = 'asc';
    } else {
      this.state.activeEffective = 0;
      this.state.pageData.order_effective = null;
    }
    this.sortList();
  }

  sortList() {
    this.state.pageData.page = 1
    const { activeEffective, activePrice } = this.state;
    if (activeEffective === 0 && activePrice === 0) {
      this.state.pageData.order_price = null;
      this.state.pageData.order_effective = null;
      this.state.activeDefalut = true
    } else {
      this.state.activeDefalut = false
    }
    list({
      ...this.state.pageData,
      card_status: this.state.status,
    }).then(res => {
      this.setState({
        cardRecordList: res.list
      });
    })
  }

  render() {
    const { HeaderTab, status, cardRecordList, cardShareList, activeDefalut, activePrice, activeEffective, isShowShareRemind, listCount_0, listCount_1, listCount_2, listCount_3 } = this.state;
    return (
      <View className='card-record' style={`margin-top: ${navigationBarHeight}`}>
        <NavigationBar text="我的卡券" type="home" ref={this.menuBarRef} />
        {/* 顶部切换栏 */}
        <View className="top-wrapper" style={`top: ${navigationBarHeight}`}>
          <View className="header">
            <View className="header-box" key='0' onClick={() => this.handleTabChange(0, false)}>
              <View className={classnames({
                'content': true,
                'active': 0 === status
              })}>{HeaderTab[0].val}
                ({listCount_0})
              </View>
            </View>
            <View className="header-box" key='1' onClick={() => this.handleTabChange(1, false)}>
              <View className={classnames({
                'content': true,
                'active': 1 === status
              })}>{HeaderTab[1].val}
                ({listCount_1})
              </View>
            </View>
            <View className="header-box" key='2' onClick={() => this.handleTabChange(2, false)}>
              <View className={classnames({
                'content': true,
                'active': 2 === status
              })}>{HeaderTab[2].val}
                ({listCount_2})
              </View>
            </View>
            <View className="header-box" key='3' onClick={() => this.handleTabChange(3, false)}>
              <View className={classnames({
                'content': true,
                'active': 3 === status
              })}>{HeaderTab[3].val}
                ({listCount_3})
              </View>
            </View>
            {/* {
              HeaderTab.map((res) => (
                <View className="header-box" key={res.key} onClick={() => this.handleTabChange(res.key, false)}>
                  <View className={classnames({
                    'content': true,
                    'active': res.key === status
                  })}>{res.val}
                    ({listCount_0})
                  </View>
                </View>
              ))
            } */}
          </View>
          {/* 搜索栏 */}
          {
            status === 0 &&
            <View className="select-box">
              <View className='box_category' style={'left: 5%; color:#cbad94;'}>排序</View>
              <View className='box_category' style={'left: 16%;'}>|</View>
              <View className={classnames({ 'box_value': true, 'active': activeDefalut })}
                style={'left: 24%;'} onClick={() => this.sortDefaultList()}>
                综合
              </View>
              <View className='box_value'
                style={'left: 44%;'} onClick={() => this.sortEffective()}>
                有效期
                {activeEffective === 0 && <Image src={CardArrowNone} className="card_arrow_img" />}
                {activeEffective === 1 && <Image src={CardArrowBottom} className="card_arrow_img" />}
                {activeEffective === 2 && <Image src={CardArrowTop} className="card_arrow_img" />}
              </View>
              <View className='box_value'
                style={'left: 69%;'} onClick={() => this.sortPriceList()}>
                价格
                {activePrice === 0 && <Image src={CardArrowNone} className="card_arrow_img" />}
                {activePrice === 1 && <Image src={CardArrowBottom} className="card_arrow_img" />}
                {activePrice === 2 && <Image src={CardArrowTop} className="card_arrow_img" />}
              </View>
            </View>
          }
        </View>
        {/* 转赠确认弹窗 */}
        {isShowShareRemind &&
          <View className='share-remind'>
            <Text className='share-remind-h1'>您确定转赠吗？</Text>
            <Text className='share-remind-h2'>
              点击「确认转赠」，将前往微信界\n面选择好友赠送，确认后不可撤销；\n若转赠未成功，礼券将在72小时后\n自动退回您的卡包。
              {/* 即将前往微信界面选择好友转赠, \n本次操作不可撤销, 若转赠未成功, \n72小时后将自动退回您的卡包。 */}
              {/* <Text>即将前往微信界面选择好友转赠, \n本次操作不可撤销, 若转赠未成功, \n72小时候将自动退回您的卡包</Text> */}
              {/* <View>即将前往微信界面选择好友转赠, </View> */}
              {/* <Text>本次操作不可撤销, 若转赠未成功,</Text> */}
              {/* <Text>72小时候将自动退回您的卡包</Text> */}
            </Text>
            <Image className='share-remind-bg' src={CardClaimSuccess}></Image>
            <Button className="share-remind-action share-remind-action-confirm" open-type="share" data-item={card}>确认转赠</Button>
            <Button className='share-remind-action share-remind-action-cancle' onClick={() => this.hiddenShareRemind()}>取 消</Button>
          </View>
        }
        {(isShowShareRemind) && <View className='card-record-shadow'></View>}
        {/* 无数据的底图 */}
        {
          !cardRecordList.length && status != 2 && <View className="empty-box">
            <Image src={Empty} className="empty" />
            <View className="tip">暂无信息</View>
          </View>
        }
        {
          !cardShareList.length && status == 2 && <View className="empty-box">
            <Image src={Empty} className="empty" />
            <View className="tip">暂无信息</View>
          </View>
        }
        {/* 卡券列表 */}
        <ScrollView
        style={`top: ${status > 0 ? 80 : 180}rpx`}
          className='scroll_view'
          scrollY
          scrollWithAnimation
          onScrollToLower={this.onScrollToLower}
        >
          <View
            className="card-list">
            {
              cardRecordList.map(card => (
                <View className="card">
                  <View className="card-line">
                    <Image src={CardBg} alt="" className="card-bg" />
                    <View className='card-attr'>中鹿岛</View>
                    <View className='card-name'>{card.has_goods.goods_name}</View>
                    <View className='card-des'>{card.has_goods.goods_desc}</View>
                    <View className='card-validity'>
                      有效期至{card.deadline_time > 0 ? timeFormat(card.deadline_time, 'yyyy年MM月dd日') : '永久'}止
                    </View>
                    <View className='card-number'>
                      NO.{card.card_no}
                    </View>
                    {status == 0 && card.share_status !== 1 &&
                      <View>
                        {/* <Button className="card-action card-action-button" style={'top: 10%'} open-type="share" data-item={card}>转赠</Button> */}
                        <View className='card-action' style={'top: 10%'} onClick={() => this.showShareRemind(card)}>微信转赠</View>
                        <View className='card-action' style={'top: 40%'} onClick={() => this.goShop(card.has_goods.goods_id, card.id)}>立即兑换</View>
                      </View>
                    }
                    {status == 0 && card.share_status === 1 &&
                      <View>
                        <Button className="card-action card-action-button" style={'top: 25%; background-color: #ad793d; color: #e7b394'}>转赠中</Button>
                        {/* <View className='card-action' style={'top: 40%'} onClick={() => this.cancelShare(card.id)}>撤销转赠</View> */}
                      </View>
                    }
                    {status == 1 &&
                      <Image src={CardUsedImg} alt="" className="card-action-img" />
                    }
                    {status == 2 &&
                      <Image src={CardSharedImg} alt="" className="card-action-img" />
                    }
                    {status == 3 &&
                      <Image src={CardExpiredImg} alt="" className="card-action-img" />
                    }
                  </View>
                </View>
              ))
            }
            {
              cardShareList.map(card => (
                <View className="card">
                  <View className="card-line">
                    <Image src={CardBg} alt="" className="card-bg" />
                    <View className='card-attr'>中鹿岛</View>
                    <View className='card-name'>{card.has_card.has_goods.goods_name}</View>
                    <View className='card-des'>{card.has_card.has_goods.goods_desc}</View>
                    <View className='card-validity'>
                      有效期至{card.has_card.deadline_time > 0 ? timeFormat(card.has_card.deadline_time, 'yyyy年MM月dd日') : '永久'}止
                    </View>
                    <View className='card-number'>
                      NO.{card.has_card.card_no}
                    </View>
                    <Image src={CardSharedImg} alt="" className="card-action-img" />
                  </View>
                </View>
              ))
            }
            <View className="card"></View>
          </View>
        </ScrollView>


        <View className="tabBar" >
          <TabBar statusS={this.state.statusS}></TabBar>
        </View>
      </View>
    )
  }
}
